package com.song.week.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.week.domain.TestUser;
import com.song.week.dto.LoginDto;
import com.song.week.service.FileStorageService;
import com.song.week.service.TestUserService;
import com.song.week.utils.AppJwtUtil;
import com.song.week.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @author TonySong
 * @date 2024/6/11 0011
 * @time 16:28
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private TestUserService testUserService;

    @Resource
    private FileStorageService fileStorageService;


    private String avater="";
    // 登录（生成token）
    @PostMapping("/login")
    public R login(@RequestBody LoginDto dto){
       return testUserService.login(dto);
    }

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file){
        String fname = file.getOriginalFilename();
        fname = UUID.randomUUID().toString() + fname.substring(fname.lastIndexOf("."));

        try {
            avater=this.fileStorageService.uploadImgFile(fname, fname, file.getInputStream());
            System.err.println("图片路径-------->"+avater);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return R.error(500,"上传头像失败");
        }
        return R.ok();
    }

    // 注册（minio上传头像）
    @PostMapping("/register")
    public R register(@RequestBody TestUser user){

        //随机生成盐
        String salt = new Random().nextInt(999999) + "";
        //保存盐到数据库中
        user.setSale(salt);
        //加密
        String md5Password = DigestUtils.md5DigestAsHex((user.getPassword()+salt).getBytes());
        //保存加密后的密码
        user.setPassword(md5Password);
         //设置头像
        user.setAvter(avater);
        this.testUserService.save(user);
        return R.ok();
    }
    // 删除(逻辑删除)
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer id){
        this.testUserService.removeById(id);
        return R.ok();
    }
    // 分页
    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer offset,
                  @RequestParam(defaultValue = "10") Integer size){

        Page<TestUser> page = this.testUserService.page(new Page<>(offset, size), new LambdaQueryWrapper<TestUser>());
        return R.success(page);
    }
}
